package com.zy.stock.autosell;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Component
public class Transform {


    private static final String TX_STOCK_URL = "http://qt.gtimg.cn/q=";


    private static final Pattern NUMBER_PATTERN = Pattern.compile("\\d{14}");



    static final RestTemplate REST_TEMPLATE = new RestTemplate();





    public List<GidDto> transform(Collection<String> stockNos) {
        if (CollectionUtils.isEmpty(stockNos)) {
            return Collections.emptyList();
        }
        List<GidDto> gidDtoList = new ArrayList<>(stockNos.size() * 2);
        ArrayList<String> array = new ArrayList<>(stockNos);
        String stockNoStr = String.join(",", array);
        ResponseEntity<String> responseEntity = REST_TEMPLATE.getForEntity(TX_STOCK_URL + stockNoStr, String.class);
        try {
            if (responseEntity.getStatusCode() == HttpStatus.OK) {
                String[] bodies = responseEntity.getBody().split(";");
                for (int i = 0; i < bodies.length && i < array.size(); i++) {
                    String body = bodies[i];
                    body = body.replace("\r", "").replace("\n", "");
                    GidDto gidDto = txBodyToGid(body);
//                    GidDto gidDto = bodyToGid(stockNo, body);
                    if (gidDto != null) {
                        gidDtoList.add(gidDto);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return gidDtoList;
        }
        return gidDtoList;
    }

    private GidDto txBodyToGid(String body){
        String[] split = body.split("~");

        if (split.length <= 1){
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat hkSdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");

        // 仅有数字的股票代码
        String stockNoWithNotMarket = split[2];


        String market = StockUtils.getMarket(stockNoWithNotMarket);
        GidDto dto = new GidDto();
        String stockNo = market + stockNoWithNotMarket;
        if (StockUtils.SH.equalsIgnoreCase(market) || StockUtils.SZ.equalsIgnoreCase(market) || StockUtils.BJ.equalsIgnoreCase(market)
        || StockUtils.HK.equals(market)) {
            dto.setStockNo(stockNo);
            dto.setName(split[1]);
            dto.setNowPrice(new BigDecimal(split[3]));
            dto.setClosePrice(new BigDecimal(split[4]));
            dto.setOpenPrice(new BigDecimal(split[5]));
            if (StockUtils.HK.equals(market)){
                dto.setTradeNum(new BigDecimal(split[6]));
            }else {
                dto.setTradeNum(new BigDecimal(split[6]).multiply(new BigDecimal("100")));
            }

            // 外盘
            try {
                dto.setOuterDisc(new BigDecimal(split[7]));
            }catch (Exception ignored){

            }
            try{
                // 内盘
                dto.setInvol(new BigDecimal(split[8]));
            }catch (Exception ignored){

            }

            // 买一数量
            dto.setBuy1N(new BigDecimal(split[10]).multiply(new BigDecimal("100")));
            dto.setBuy2N(new BigDecimal(split[12]).multiply(new BigDecimal("100")));
            dto.setBuy3N(new BigDecimal(split[14]).multiply(new BigDecimal("100")));
            dto.setBuy4N(new BigDecimal(split[16]).multiply(new BigDecimal("100")));
            dto.setBuy5N(new BigDecimal(split[18]).multiply(new BigDecimal("100")));
            // 买1价格
            dto.setBuy1M(new BigDecimal(split[9]));
            dto.setBuy2M(new BigDecimal(split[11]));
            dto.setBuy3M(new BigDecimal(split[13]));
            dto.setBuy4M(new BigDecimal(split[15]));
            dto.setBuy5M(new BigDecimal(split[17]));

            // 卖一数量
            dto.setSell1N(new BigDecimal(split[20]).multiply(new BigDecimal("100")));
            dto.setSell2N(new BigDecimal(split[22]).multiply(new BigDecimal("100")));
            dto.setSell3N(new BigDecimal(split[24]).multiply(new BigDecimal("100")));
            dto.setSell4N(new BigDecimal(split[26]).multiply(new BigDecimal("100")));
            dto.setSell5N(new BigDecimal(split[28]).multiply(new BigDecimal("100")));

            dto.setSell1M(new BigDecimal(split[19]));
            dto.setSell2M(new BigDecimal(split[21]));
            dto.setSell3M(new BigDecimal(split[23]));
            dto.setSell4M(new BigDecimal(split[25]));
            dto.setSell5M(new BigDecimal(split[27]));

            // 静态市盈率
            try {
                dto.setJpe(new BigDecimal(split[53]));
            }catch (Exception e){
                dto.setJpe(BigDecimal.ZERO);
            }

            // 动态市盈率
            try {
                dto.setPe(new BigDecimal(split[52]));
            }catch (Exception e){
                dto.setPe(BigDecimal.ZERO);
            }

            // ttm
            try {
                dto.setTtm(new BigDecimal(split[39]));
            }catch (Exception e){
                dto.setTtm(BigDecimal.ZERO);
            }

            try {
                Matcher matcher = NUMBER_PATTERN.matcher(split[30]);
                if (matcher.find()){
                    dto.setDatetime(sdf.parse(split[30]));
                }else {
                    dto.setDatetime(hkSdf.parse(split[30]));
                }
                dto.setTimeStamp(dto.getDatetime().getTime());
                dto.setDate(sdf1.format(dto.getDatetime()));
            } catch (Exception ignored) {
            }
            // 涨跌金额
            dto.setDiffMoney(new BigDecimal(split[31]));
            dto.setDiffRate(new BigDecimal(split[32]));
            // 最高价
            dto.setTodayMax(new BigDecimal(split[33]));
            // 最低价
            dto.setTodayMin(new BigDecimal(split[34]));
            // 换手率
            try {
                dto.setTurnover(new BigDecimal(split[38]));
            }catch (Exception e){
                dto.setTurnover(BigDecimal.ZERO);
            }
            // ttm市盈率
//            split[39]
            // 振幅
            dto.setSwing(new BigDecimal(split[43]));
            // 流通市值
            try {
                dto.setCirculationValue(new BigDecimal(split[44]));
            }catch (Exception e){
                dto.setCirculationValue(BigDecimal.ZERO);
            }
            // 总市值
            try {
                dto.setAllValue(new BigDecimal(split[45]));
            }catch (Exception e){
                dto.setAllValue(BigDecimal.ZERO);
            }


            if (StockUtils.isA(stockNo)){
                // 涨停价
                dto.setHighLimit(new BigDecimal(split[47]));
                // 跌停价
                dto.setDownLimit(new BigDecimal(split[48]));
            }

            // 量比
//            split[49]
            // 均价
            try {
                dto.setAvgPrice(new BigDecimal(split[51]));
            }catch (Exception ignored){
                dto.setAvgPrice(BigDecimal.ZERO);
            }
            ;
            // 动态市盈率
//            split[52]
            // 静态市盈率
//            split[53]


            // 最新价/成交量（手）/成交额（元）
            String s = split[35];
            if (s != null && !"".equals(s)){
                String[] split1 = s.split("/");
                if (split1.length > 0){
                    try {
                        dto.setNowPrice(new BigDecimal(split1[0]));
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                if (split1.length > 1){
                    dto.setTradeNum(new BigDecimal(split1[1]).multiply(new BigDecimal("100")));
                }
                if (split1.length > 2){
                    dto.setTradeAmount(new BigDecimal(split1[2]));
                }
            }
            return dto;
        }
        return null;
    }

}
